<template>
  <div>
    <el-row>
      <h1>用户管理</h1>
      <el-col :span="12">
        <div style="margin: 20px 20px 20px 0;width: 40%">
          <el-input v-model="searchInput"
                    placeholder="用户账号（模糊查询）"
                    @keyup.enter.native="search"
                    prefix-icon="el-icon-search"
                    clearable>
          </el-input>
        </div>
      </el-col>
      <el-col :span="12">
        <div style="margin: 20px 20px">
          <el-button type="primary" v-if="$store.state.authorities.includes('system:user:add')" @click="addUserEdit"
                     style="float:right;margin-left: 30px;">新增用户
          </el-button>
          <el-button type="danger" @click="deleteUserByIdBatch" style="float:right;">批量删除</el-button>
        </div>
      </el-col>

      <el-col :span="24">
        <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection">
          </el-table-column>
          <el-table-column
              prop="username"
              label="用户账号">
          </el-table-column>
          <el-table-column
              prop="avatar"
              label="头像">
            <template v-slot="scope">
              <el-image
                  style="width: 40px;"
                  :src="'http://localhost:8080/'+scope.row.avatar"
                  fit="fit">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
              prop="role.name"
              label="角色名称">
          </el-table-column>
          <el-table-column
              prop="dept.name"
              label="所属部门">
          </el-table-column>
          <el-table-column
              prop="sex"
              label="性别">
            <template v-slot="scope">
              {{ scope.row.sex === '0' ? "男" : "女" }}
            </template>
          </el-table-column>
          <el-table-column
              prop="phonenumber"
              label="手机号码"
              width="115px">
          </el-table-column>
          <el-table-column
              prop="status"
              label="用户状态">
            <template v-slot="scope">
              <el-switch
                  @change="setStatus(scope.row)"
                  active-value="0"
                  inactive-value="1"
                  v-model="scope.row.status"
                  active-color="#13ce61"
                  inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
              prop="deviceId"
              label="设备ID">
          </el-table-column>
          <el-table-column
              prop="updateTime"
              label="更新时间"
              width="180px">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="232px">
            <template v-slot="scope">
              <el-button @click="updateUserBtn(scope.row.userId)" size="mini">修改
              </el-button>
              <el-button @click="deleteUserBtn(scope.row.userId)" type="warning" size="mini">删除
              </el-button>
              <el-button @click="resetPwd(scope.row)" type="danger" size="mini">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col :span="24" style="margin-top: 20px;text-align: center">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="用户编辑" :visible.sync="dialogFormVisible">
      <UserEdit v-if="dialogFormVisible" :id="editId" @close-dialog="closeDialog">
      </UserEdit>
    </el-dialog>
  </div>

</template>

<script>
import request from "@/utils/request";
import UserEdit from "@/components/pages/UserEdit";

export default {
  name: "UserPage",
  components: {UserEdit},
  data() {
    return {
      // 弹窗是否打开
      dialogFormVisible: false,
      editId: 0,
      // 用户数据
      tableData: [],
      // 根据userId批量删除的
      multipleSelection: [],
      // 模糊搜索
      searchInput: "",
      // 分页的 pageSize total currentPage
      pageSize: 10,
      total: 0,
      currentPage: 1,
    }
  },
  created() {
    // 加载用户数据
    this.loadUser()
  },
  methods: {
    // 这里发送用户请求，并拼接分页信息以及username字段可进行模糊查询
    async loadUser() {
      let data = await request("user?page=" + this.currentPage + "&size=" + this.pageSize + "&username=" + this.searchInput + "&orderBy=update_time desc");
      this.tableData = data.list
      this.total = data.total
    },
    // 父子传值 返回的值，true就加载数据
    closeDialog(b) {
      this.dialogFormVisible = false;
      if (b) {
        this.loadUser()
      }
    },
    // 批量删除
    deleteUserByIdBatch() {
      let ids = []
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择你要删除的ID")
      } else {
        this.multipleSelection.map(item => {
          ids.push(item.userId)
        })
        request("user/deleteUserByIdsBatch?ids=" + ids, "DELETE").then(() => {
          this.$message.success("批量(逻辑)删除成功")
          this.loadUser()
        }).catch(() => {
          this.$message.error("批量(逻辑)删除失败")
        })
      }
    },
    // 新增用户按钮
    addUserEdit() {
      this.editId = 0
      this.dialogFormVisible = true;
    },
    // 分页
    handleSizeChange(i) {
      this.pageSize = i;
      this.currentPage = 1;
      this.loadUser()
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadUser()
    },
    // 模糊查询  请求路径拼接的
    search() {
      this.loadUser()
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 修改用户信息
    updateUserBtn(userId) {
      this.dialogFormVisible = true
      this.editId = userId
    },
    // 删除用户按钮
    deleteUserBtn(id) {
      this.$confirm('此操作将永久禁用该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request(`user?id=${id}`, "DELETE").then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.loadUser()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 重置密码操作
    resetPwd({userId, username}) {
      console.log(userId, username)
      this.$prompt(`请输入用户：${username} 重置的密码`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // 任何格式的密码都行 *
        inputPattern: /.*/,
        inputErrorMessage: '密码格式不正确'
      }).then(({value}) => {
        request(`user?userId=${userId}`, "PUT", {userId: userId, password: value}).then(() => {
          this.$message({
            type: 'success',
            message: `${username}update password success`
          });
          this.loadUser()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    // 修改用户状态
    setStatus({userId, status}) {
      request("user", "PUT", {userId: userId, status: status}).then(() => {
        this.$message.success("修改状态成功")
      }).catch(() => {
        this.$message.error("修改状态失败")
      })
    },
  }
}
</script>

<style scoped>

</style>